package a07_二叉树;

/**
 * <p>
 * a09_平衡二叉树
 * </p>
 * 什么是平衡二叉树
 * 二叉树的任何节点的左右子树的高度差不超过1
 *
 *
 *
 * @author flyduck
 * @since 2024-08-29
 */
public class a12_平衡二叉树复习1 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,
                new TreeNode(2,
                        new TreeNode(3,
                                new TreeNode(4, null, null),
                                null),
                        null),
                new TreeNode(2,
                        new TreeNode(3,
                                new TreeNode(4, null, null),
                                null),
                        null)
        );
        boolean balanced = isBalanced(root);
        System.out.println(balanced);
    }



    //平衡二叉树：左右子数的高度差不能大于1
    public static boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return leftHeight != -1 && rightHeight != -1 && Math.abs(leftHeight - rightHeight) <= 1;
    }

    public static int getHeight(TreeNode node){
        if (node == null) {
            return 0;
        }
        int leftHeight = getHeight(node.left);
        if(leftHeight == -1){
            return -1;
        }
        int rightHeight = getHeight(node.right);
        if(rightHeight == -1){
            return -1;
        }
        if(Math.abs(leftHeight - rightHeight) > 1){
            return -1;
        }else {
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }



}
